CREATE PROCEDURE [dbo].[PatientSave]
@Id					UNIQUEIDENTIFIER,
@PatientNo			NVARCHAR(10),
@Title				NVARCHAR(50),
@FirstName			NVARCHAR(50),
@LastName			NVARCHAR(50),
@Gender				NCHAR(1),
@DOB				DATETIME,
@AddressLine1		NVARCHAR(50),
@AddressLine2		NVARCHAR(50),
@City				NVARCHAR(50),
@State				NVARCHAR(50),
@Country			NVARCHAR(50),
@ZipCode			NVARCHAR(50),
@ConsentToCallBack	BIT,
@ContactNumber		NVARCHAR(50),
@Email				NVARCHAR(100),
@ReferrerId			UNIQUEIDENTIFIER
AS

DECLARE	@RowCount AS INT
DECLARE @Error AS INT

UPDATE	Patient
SET		PatientNo			= ISNULL(@PatientNo, PatientNo),
		Title				= ISNULL(@Title, Title), 	
		FirstName			= ISNULL(@FirstName, FirstName),
		LastName			= ISNULL(@LastName, LastName), 
		Gender				= ISNULL(@Gender, Gender), 
		DOB					= ISNULL(@DOB, DOB), 	
		AddressLine1		= ISNULL(@AddressLine1, AddressLine1),
		AddressLine2		= ISNULL(@AddressLine2, AddressLine2),
		City				= ISNULL(@City, City),
		State				= ISNULL(@State, State)	, 
		Country				= ISNULL(@Country, Country),
		ZipCode				= ISNULL(@ZipCode, ZipCode), 
		ConsentToCallback	= ISNULL(@ConsentToCallback,ConsentToCallback),
		ContactNumber		= ISNULL(@ContactNumber,ContactNumber),
		Email				= ISNULL(@Email, Email),
		ReferrerId			= ISNULL(@ReferrerId, ReferrerId)
WHERE	Id = @Id

SELECT @Error = @@ERROR, @RowCount = @@ROWCOUNT

IF @Error  <> 0
BEGIN
	RAISERROR('ERROR::PatientSave:Error in',16,1)
END

IF @RowCount  > 0
BEGIN
	RETURN @RowCount 
END

--	If adding for first time enter all the details including Id
INSERT	INTO Patient (Id, PatientNo, Title,  FirstName, LastName, Gender, DOB, AddressLine1, AddressLine2, City, State, Country, ZipCode, ConsentToCallback, ContactNumber, Email, ReferrerId)
VALUES	(@Id, @PatientNo, @Title, @FirstName, @LastName, @Gender, @DOB, @AddressLine1, @AddressLine2, @City, @State, @Country, @ZipCode, @ConsentToCallback, @ContactNumber, @Email, @ReferrerId)

SELECT	@Error = @@ERROR, @RowCount = @@ROWCOUNT

IF @Error  <> 0
BEGIN
	RAISERROR('ERROR::PatientNew:Error in',16,1)
END

RETURN @RowCount